<template>
    <div class="panel-account">
        <el-form :rules="accountRules" size="large" status-icon ref="formRef" :model="account" label-width="60"
            label-position="left">
            <el-form-item label="帐号" prop="name">
                <el-input type="text" v-model="account.name" clearable />
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input show-password v-model="account.password" clearable />
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormRules, ElForm } from 'element-plus'
import { ElMessage } from 'element-plus'
import { accountLoginRequest } from '@/service/login/login'
import useLoginStore from '@/store/login/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'

//1.定义表单数据
const account = reactive<IAccount>({
    name: localCache.getCache('name') ?? '',
    password: localCache.getCache('password') ?? ''
})
//2.定义校验规则
const accountRules: FormRules = {
    name: [
        { message: '必须输入帐号信息', required: true, trigger: 'blur' },
        { message: '必须是6~20位数字或字母组成', trigger: 'blur', pattern: /^[a-z0-9]{6,20}$/ }
    ],
    password: [
        { message: '必须输入密码信息', required: true, trigger: 'blur' },
        { message: '必须是3位以上的数字或字母组成', trigger: 'blur', pattern: /^[a-z0-9]{3,}$/ }
    ]
}
// 3.执行账号的登录逻辑
const formRef = ref<InstanceType<typeof ElForm>>()

const loginstore = useLoginStore()

function loginAction(isRemPwd?: boolean) {
    console.log('account-action', isRemPwd)
    formRef.value?.validate((valid) => {
        if (valid) { // 验证成功
            // 1.获取用户输入的账号密码
            const name = account.name;
            const password = account.password;

            // 2.向服务器发送网络请求
            loginstore.loginAccountAction({ name, password }).then(() => {
                // 3.判断是否记住密码
                if (isRemPwd) {
                    localCache.setCache('name', name)
                    localCache.setCache('password', password)
                } else {
                    localCache.removeCache('name')
                    localCache.removeCache('password')
                }
            })

        } else { // 验证失败
            ElMessage.error('请输入正确的格式后再登录')
        }
    })

}
defineExpose({
    loginAction
})
</script>
<style lang="less" scoped>
.panel-account {
    overflow: auto;
}
</style>
